import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import loadDynamicRouter from "@/router/dynamic-router";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/404', '/register']
Vue.use(VueRouter);
const routes = [
    {
        path: '',
        component: () => import('@/views/index'),
        children:[
            {
                path:'/bpmn/design/config',
                component: () => import('@/views/workflow/bpm/index'),
            }
        ]
    },
    {
        path: '/login',
        component: () => import('@/views/login/index')
    },
    {
        path: '*',
        component: () => import('@/components/Exception/404')
    }
];

const router = new VueRouter({
    mode: 'history',
    routes
})

let tokenExists = () => {
    let token = store.getters.token;
    return token !== undefined && token !== null && token.trim() !== "" && token !== "null" && token !== "undefined";
}

let getFirstMenuUrl = (menus)=>{
    let menu = menus[0];
    if(menu.children !== undefined && menu.children.length > 0){
        return getFirstMenuUrl(menu.children);
    }
   return menu.path;
}

router.beforeEach((to, from, next) => {
    NProgress.start();
    if (tokenExists()) {
        if (to.path === "/login") {
            next({path: "/"})
            NProgress.done();
        } else {
            if (store.getters.menus === undefined) {
                store.dispatch("GetUserInfo").then(() => {});
                loadDynamicRouter(router).then(() => {
                    try {
                        next({...to, replace: true}) // 确保addRoutes()时动态添加的路由已经被完全加载上去
                    } catch (e) {
                        // eslint
                    }
                });
            } else {
                if(store.getters.menus.length > 0 && to.path === "/"){
                    next({path:getFirstMenuUrl(store.getters.menus)});
                }else{
                    next();
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`)
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done()
})

export default router;